package com.pig4cloud.pigx.common.customize.i18n.interceptors;

import org.apache.logging.log4j.util.Strings;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: Dapp自定义国际语言拦截器
 * @Date: 2022/8/29 16:58
 */
public class CustomerLocaleChangeInterceptors extends LocaleChangeInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
		// 从URL中读取
		String newLocale1 = request.getParameter(this.getParamName());
		// 从heaers头部中读取
		String newLocale2 = request.getHeader(this.getParamName());
		String newLocale = null;
		if (Strings.isNotBlank(newLocale1)) {
			newLocale = newLocale1;
		} else if (Strings.isNotBlank(newLocale2)) {
			newLocale = newLocale2;
		}
		if (newLocale != null && this.checkHttpMethod(request.getMethod())) {
			LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
			if (localeResolver == null) {
				throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
			}

			try {
				localeResolver.setLocale(request, response, this.parseLocaleValue(newLocale));
			} catch (IllegalArgumentException var7) {
				if (!this.isIgnoreInvalidLocale()) {
					throw var7;
				}

				this.logger.debug("Ignoring invalid locale value [" + newLocale + "]: " + var7.getMessage());
			}
		}

		return true;
	}

	private boolean checkHttpMethod(String currentMethod) {
		String[] configuredMethods = this.getHttpMethods();
		if (ObjectUtils.isEmpty(configuredMethods)) {
			return true;
		} else {
			String[] methods = configuredMethods;
			int length = configuredMethods.length;

			for (int i = 0; i < length; ++i) {
				String configuredMethod = methods[i];
				if (configuredMethod.equalsIgnoreCase(currentMethod)) {
					return true;
				}
			}
			return false;
		}
	}
}
